package com.peza.mines;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Board {

	
	private int[][] board;
	
	private Field [][] fieldGrid;
	
	private int size;
	
	
	public Board (int size, int mines){
		this.size = size;
		board = new int[size][size];
		populate(createMines(mines));
		labelFields();
	}
	
	
	/** puts the board and the mines together **/
	private void populate(List<Integer> mines){

		int counter = 0;
		for (int y = 0; y < size; y++){
			for (int x = 0; x < size; x++){
				if (mines.contains(counter)){
					board[y][x] = 9;
				} else {
					board[y][x] = 0;
				}
			counter++;
			}
		}
	}
	
	
	/** Returns a list of ints representing minefield IDs **/ 
	private List<Integer> createMines(int mines) {
		int counter = 0;
		List<Integer> fields = new ArrayList<Integer>();
		
		/** get minefields **/
		while (counter < mines){
			int random = getRandom(0, (size*size)-1);
			if (!fields.contains(random)){
				fields.add(random);
				counter++;
			}
		}
		return fields;
	}	

	/** Put number labels on grid fields**/
	private void labelFields(){
		for (int y = 0; y < size; y++){
			for (int x = 0; x < size; x++){
				int counter = 0;
				
				/** check all surrounding fields **/
				/** but do not check minefields **/
				if (board[y][x] != 9){
					
					for (int offsety = -1; offsety < 2; offsety++){
						for (int offsetx = -1; offsetx < 2; offsetx++ ){
							try {
								int ycoord = y+offsety;
								int xcoord = x+offsetx;
								/** do not check the center field **/
								if (!(y == ycoord && x == xcoord)){
									/** if checked field is a mine */
									if (board[ycoord][xcoord] == 9){
										counter++;
									}
								}
							} catch (ArrayIndexOutOfBoundsException e) {
								/** nothing to do here, just move to next iteration **/
							}	
							
						}
					}
				/** set counter as new field value **/	
				board[y][x] = counter;
				}
			}		
		}
		
	}
	
	
	/** Return a random integer between min and max **/
	private int getRandom(int min, int max){
		Double value = (min + Math.random()*max);
		return (int) Math.round(value);
	}

	
	
	public int[][] getBoard() {
		return board;
	}

	public void setBoard(int[][] board) {
		this.board = board;
	}
	
	public boolean isFree(int x, int y){
		
		if (board[y][x] == 0){
			return true;
		} else {
			return false;
		}
		
	}
	
	
	
	
	
	
	@Override
	public String toString(){
		StringBuffer buffer = new StringBuffer();		
		for (int y = 0; y < size; y++){
			for (int x = 0; x < size; x++) {
				buffer.append(board[y][x] + "\t");
			}
			buffer.append("\n");
		}
		return buffer.toString();
	}
	
}
